package com.wjk.cms.aop;


import com.wjk.cms.auth.AuthContext;
import com.wjk.cms.util.ContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Component
@Aspect
@Order(1)
public class BenchmarkAopAction {

    @Pointcut("execution(public * com.wjk.cms.controller..*Controller.*(..))")
    public void controllerAspect() {

    }

    @Around("controllerAspect()")
    public Object doController(ProceedingJoinPoint point) throws Throwable {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        try {
            return point.proceed();
        } finally {
            HttpServletRequest request = ContextUtil.getHttpServletRequest();
            String prompt = request == null ? "Benchmark> EMPTY URI - " : "Benchmark> " + request.getRequestURI() + " - ";
            String message = "User[" + AuthContext.get() + "]";
            stopWatch.stop();
            if (stopWatch.getTime() > 100) {
                log.warn(prompt + stopWatch.getTime() + "ms" + " - " + message);
            } else {
                log.info(prompt + stopWatch.getTime() + "ms" + " - " + message);
            }
        }
    }

}
